#!/usr/bin/python3
# -*- coding: utf-8 -*-
from uiautomation import WindowControl  # 引入uiautomation库中的WindowControl类，用来进行图像识别和模拟操作
from urllib.parse import urlencode
import requests
import urllib
import json  # 处理网页数据
from sql import SQLite

# 数据库查询数据
db_name = "study.db"
sqlite = SQLite(db_name)
sqlite.connect_db()


def get_weather(sqlite, city, which_day):
    city_name = (city,)
    sql_cmd = "select * from city where city_name=?"
    query_res = sqlite.query_data(sql_cmd=sql_cmd, name=city_name)
    if len(query_res) == 0:
        return "暂不知道您在说什么，请发城市+哪一天天气\n例如：渭南今天天气"
    city_id = query_res[0][0]
    url = f"http://t.weather.sojson.com/api/weather/city/{city_id}"  # 获取用户输入的城市进行查询
    request = url
    re = requests.get(request)
    rep = re.json()
    '''
    获取网页中的响应的元组变量
    '''
    city_info = rep.get('cityInfo')

    wea_data = rep.get('data')
    curr_shidu = wea_data.get('shidu')
    curr_pm25 = wea_data.get('pm25')
    curr_pm10 = wea_data.get('pm10')
    curr_quality = wea_data.get('quality')
    curr_wendu = wea_data.get('wendu')

    forecast_data = wea_data.get('forecast')
    day_index = 0
    if which_day == "今天":
        day_index = 0
    elif which_day == "明天":
        day_index = 1
    elif which_day == "后天":
        day_index = 2

    ymd = forecast_data[day_index].get('ymd')  # 日期
    week = forecast_data[day_index].get('week')
    wind = forecast_data[day_index].get('fx')  # 风向
    wind_power = forecast_data[day_index].get('fl')  # 风力
    high_temp = forecast_data[day_index].get('high')  # 最高温度
    low_temp = forecast_data[day_index].get('low')
    notice = forecast_data[day_index].get('notice')
    weather = forecast_data[day_index].get('type')  # 天气

    # 今日天气
    res = f"{city} {which_day}天气\n"
    res += f"{ymd} {week} \n"
    res += f"天气 {weather}\n"
    res += f"最高温度 {high_temp}\n"
    res += f"最低温度 {low_temp}\n"
    res += f"湿度 {curr_shidu}\n"
    res += f"PM2.5 {curr_pm25}\n"
    res += f"空气质量 {curr_quality}\n"
    res += f"风向 {wind}\n"
    res += f"风力 {wind_power}\n"
    res += f"{notice}\n"

    return res


# 绑定微信主窗口
wx = WindowControl(
    Name='微信',
    searchDepth=1
)

# 切换窗口
wx.ListControl()
wx.SwitchToThisWindow()
# 寻找会话控件绑定
hw = wx.ListControl(Name='会话')
# 死循环接收消息
while True:
    # 从查找未读消息
    we = hw.TextControl(searchDepth=4)

    # 死循环维持，没有超时报错
    while not we.Exists():
        pass

    # 存在未读消息
    if we.Name:
        # 点击未读消息
        we.Click(simulateMove=False)
        # 读取最后一条消息
        message = wx.ListControl(Name='消息').GetChildren()[-1].Name
        if len(message) <= 4:
            wx.SendKeys("暂不知道您在说什么，请发城市+哪一天天气", waitTime=0.1)
            # 发送消息 回车键
            wx.SendKeys('{Enter}', waitTime=0.1)
            continue
        city_name = message[:-4]
        which_day = message[-4:-2]
        res = get_weather(sqlite, city_name, which_day)

        # 将数据输入
        # 替换换行符号
        # wx.SendKeys(ar[0].replace('{br}', '{Shift}{Enter}'), waitTime=1)
        wx.SendKeys(res.replace('\n', '{Shift}{Enter}'), waitTime=0.1)
        # 发送消息 回车键
        wx.SendKeys('{Enter}', waitTime=0.1)
